import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { Table, Spin, Drawer, Select, Button, ConfigProvider } from 'antd';
import moment from 'moment';
import zhCN from 'antd/es/locale/zh_CN';
import { tableLocale } from '@/tool/components/PageEmpty';
import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { PageLoading, TRDefault } from '@/components/index.js';
import { operateLogModal, selectedCircle, upHide, downShow } from '@/assets';
import TRNotification from '#/utils/notification';
import { DownSquareOutlined, UpSquareOutlined } from '@ant-design/icons';
import { getPhoneUserName, getPhoneOperationLog } from '../../services';
import { getDataSource } from '../../helper';

const { Column } = Table;

function ItemContent({ item }) {
  return (
    <div className={styles.container}>
      {item.status !== null ? (
        <div className={styles.statusBox}>
          调整状态为
          <div className={`${item.status ? styles.green : styles.red} ${styles.box}`}>
            {item.status ? '启用' : '停用'}
          </div>
        </div>
      ) : (
        ''
      )}
      <Table
        className={styles.table}
        dataSource={[item.details]}
        bordered={true}
        locale={tableLocale}
        pagination={false}
      >
        {Object.entries(item.details).map((t) => (
          <Column title={t[0]} align="center" dataIndex={t[0]} key={t[0]} />
        ))}
      </Table>
    </div>
  );
}

function OperateLogModal({ onPress }) {
  const [userName, setUserName] = useState(),
    [showOperateLog, setShowOperateLog] = useState(true),
    [loading, setLoading] = useState(true),
    [spinloading, setSpinloading] = useState(true),
    [operateLogList, setOperateLogList] = useState([]),
    [userList, setUserList] = useState([]);

  useEffect(() => {
    initHandle();
  }, []);

  const initHandle = () => {
    // setShowOperateLog(true);
    // 获取全部方案列表
    fetchProgramsAll();
    fetchOperateLogsFunc();
  };

  const fetchProgramsAll = async () => {
    setLoading(true);
    const res = await getPhoneUserName();
    if (res?.statusCode === HttpCode.SUCCESS) {
      const data = res?.data?.map((t) => ({
        label: t,
        value: t,
      }));
      setUserList(data);
    } else {
      TRMessage.error(res?.message || '获取操作人列表失败');
    }
    setLoading(false);
  };

  async function fetchOperateLogsFunc() {
    setSpinloading(true);
    const res = await getPhoneOperationLog({ userName });
    if (res?.statusCode === HttpCode.SUCCESS) {
      setOperateLogList(getDataSource(res.data));
    } else {
      TRMessage.error(res?.message || '获取操作日志列表失败');
    }
    setSpinloading(false);
  }

  const changeShowDetail = (index) => {
    let data = JSON.parse(JSON.stringify(operateLogList));
    data[index].showDetail = !data[index].showDetail;
    setOperateLogList(data);
  };

  const _onCloseDrawer = () => {
    setShowOperateLog(false);
    onPress({ index: 0 });
  };

  const render = () => {
    if (loading) return <PageLoading />;
    return (
      <ConfigProvider locale={zhCN}>
        <div className={styles.head}>
          <Select
            className={styles.operator}
            options={userList}
            value={userName}
            onChange={(e) => {
              setUserName(e);
            }}
          />
          <Button
            style={{ width: 98, height: 32 }}
            type="primary"
            onClick={() => {
              fetchOperateLogsFunc();
            }}
          >
            查询
          </Button>
        </div>
        {operateLogList?.length ? (
          <Spin spinning={spinloading}>
            <div className={styles.content}>
              {operateLogList.map((item, index) => (
                <div className={`${styles.item} ${item.showDetail ? styles.show : ''}`} key={index}>
                  <div className={styles.itemHeader}>
                    <div className={styles.left}>
                      {index === 0 ? (
                        // <img src={selectedCircle} />
                        <div className={styles.firstCircle}>
                          <div />
                        </div>
                      ) : (
                        <div className={styles.circle} />
                      )}
                      <span className={styles.dateTime}>
                        {moment(item.createdAt).format('YYYY.MM.DD HH:mm:ss')}
                      </span>
                      <span className={styles.operateType}>{item.title}</span>
                      {/* <img
                        className={styles.arrow}
                        src={item.showDetail ? upHide : downShow}
                        onClick={() => changeShowDetail(index)}
                      /> */}
                      {item.showDetail ? (
                        <UpSquareOutlined
                          onClick={() => changeShowDetail(index)}
                          className={styles.arrow}
                        />
                      ) : (
                        <DownSquareOutlined
                          onClick={() => changeShowDetail(index)}
                          className={styles.arrow}
                        />
                      )}
                    </div>

                    <div className={styles.right}>
                      <span className={styles.label}>操作人：</span>
                      <span className={styles.value}>{item.userName}</span>
                    </div>
                  </div>
                  <div className={styles.itemContent}>
                    <ItemContent index={index} item={item} />
                  </div>
                </div>
              ))}
            </div>
          </Spin>
        ) : (
          <TRDefault type="empty" />
        )}
      </ConfigProvider>
    );
  };

  return (
    <Drawer
      className={styles.operateLogModal}
      title={
        <div className={styles.modalTitle}>
          <img src={operateLogModal} />
          <span className={styles.text}>变更记录</span>
        </div>
      }
      width={960}
      footer={null}
      visible={showOperateLog}
      onClose={_onCloseDrawer}
    >
      {render()}
    </Drawer>
  );
}

class MyDrawer {
  __key__ = '';

  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <OperateLogModal
            {...props}
            onPress={(result) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new MyDrawer();
